#!/usr/bin/env python

##########################################################################
# File Name: base.py
# Author: baohua
# Mail: liubaohuachina@163.com
# Create Time: 2020/03/24 08:40:04
# Version: 1.0
# Description:
##########################################################################

import datetime
import functools

import tornado.escape
import tornado.web
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker

from .config import config
from .utils import response

engine = create_engine(
    "mysql+pymysql://%(DB_USER)s:%(DB_PASS)s@%(DB_SVR)s:%(DB_PORT)s/%(DB_NAME)s?charset=utf8"
    % config, echo=False, pool_recycle=7200)

# DB_Session = scoped_session(sessionmaker(bind=engine))()
DB_Session = sessionmaker(bind=engine)()
# DB_Session = sessionmaker(bind=engine)


def login_required(method):
    """ Decorate methods with this to require that the user be logged in."""
    @functools.wraps(method)
    def wrapper(self, *args, **kwargs):
        # self,RequestHandler实例对象
        if not self.get_argument("token", ""):
            self.write(response(code='101001', desc='未登陆'))
            return

        # self.current_user 会调用BaseHandler的get_current_user方法
        if not self.current_user:
            self.write(response(code='102000', desc='不存在该用户'))
            return

        # FIXME 缺少权限检测

        return method(self, *args, **kwargs)

    return wrapper


class BaseHandler(tornado.web.RequestHandler):
    def __init__(self, application, request, **kwargs):
        super(BaseHandler, self).__init__(application, request, **kwargs)

    def initialize(self):
        self.db = DB_Session
        # self.db = DB_Session()

    def on_finish(self):
        print("on_finish")
        # self.db.close()

    def get_current_user(self):
        pass

    def write_error(self, code, **kwargs):
        if self.request.method == "POST":
            self.write({"code": code, 'reason': self._reason})
            self.finish()
        else:
            self.finish('<html><head><meta charset="UTF-8"><title>%(code)d: %(message)s</title>'
                "<body>%(code)d: %(message)s</body></html>"
                % {"code": code, "message": self._reason})
